<template>
  <div class="app-container">
    <el-form ref="placeCodeForm" v-loading="formLoading" :rules="rules" :model="form" label-position="top">
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="LOGO" prop="logo" style="width: 800px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.logo" :src="form.logo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="中介名称" prop="name" style="width: 400px">
            <el-input v-model="form.name" placeholder="请输入中介名称" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址" prop="address" style="width: 400px">
            <div style="display: flex;">
              <el-input v-model="form.address" placeholder="请选择地址" disabled  />
              <el-button size="mini" style="margin-left: 10px" icon="el-icon-position" type="primary" @click="showMap=true">选择位置</el-button>
            </div>
            <el-dialog title="选择位置" v-if="showMap" :visible.sync="showMap" width="40%" :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" top="5vh" >
              <iframe id="mapPage" style="width: 100%;height: 500px" frameborder=0
                      src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=RSQBZ-R2NER-KFMWS-W6OZN-UXMTE-H4BIF&referer=91885App">
              </iframe>
              <span slot="footer" class="dialog-footer">
            <el-button type="primary" class="primary"  @click="showMap = false">确 定</el-button>
          </span>
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="联系电话" prop="name" style="width: 400px">
            <el-input v-model="form.mobile" placeholder="请输入联系电话" clearable  />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规模" prop="address" style="width: 400px">
            <el-select v-model="form.scale" placeholder="请选择">
              <el-option
                v-for="item in scaleTypeOption"
                :key="item.id"
                :label="item.data"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="管理后台账号" prop="userName" style="width: 400px">
            <el-input v-if="!isEdit" v-model="form.userName" placeholder="密码默认123456，中介管理员登录自行修改" clearable  />
            <el-input v-if="isEdit" v-model="form.userName" placeholder="密码默认123456，中介管理员登录自行修改" clearable  disabled="disabled"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="营业执照" prop="coverUrl" style="width: 400px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.businessLicenseUrl" :src="form.businessLicenseUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="经营许可证" prop="coverUrl" style="width: 400px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess3"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.permitUrl" :src="form.permitUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="劳务派遣证件" prop="coverUrl" style="width: 400px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess4"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.laborDispatchUrl" :src="form.laborDispatchUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="年检报告" prop="coverUrl" style="width: 400px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess5"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.annualInspectionReportUrl" :src="form.annualInspectionReportUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="其他证件" prop="coverUrl" style="width: 400px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess6"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.otherUrl" :src="form.otherUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="介绍" prop="Abstract">
            <div class="container">
              <Toolbar :editor="editor" :default-config="toolbarConfig" :mode="mode" />
              <Editor v-model="form.introduce" :default-config="editorConfig" :mode="mode" @onCreated="onCreated" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import {uploadApi} from "@/api/user";
import {getScaleApi} from '@/api/companyCode';
import axios from "axios";
import {editIntermediaryApi, getIntermediaryByIdApi} from "@/api/Intermediary";
export default {
  components: { Editor, Toolbar },
  name: 'PlaceCodeDetail',
  data(){
    return{
      editor: null,
      editor2: null,
      showMap:false,
      isEdit: false,
      liveTime:[],
      comList:{},
      userList:{},
      publishList:{},
      toolbarConfig: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      toolbarConfig2: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      editorConfig: { MENU_CONF: {
          // 配置上传图片
          uploadImage: {
            customUpload: this.uploadImageMe // this.uploadImageMe 是 methods 中的一个普通方法
          },
        },
        placeholder: ''
      },
      editorConfig2: { MENU_CONF: {}, placeholder: '' },
      mode: 'default',
      mode2: 'default',
      uploadUrl: process.env.VUE_APP_UPLOAD_API,
      dialogImageUrl: '',
      dialogVisible: false,
      scaleTypeOption: [],
      form: {
        id: null,
        logo: '',
        name: '',
        address: '',
        longitude: '',
        latitude: '',
        scale: '',
        introduce: '',
        businessLicenseUrl: '',
        permitUrl: '',
        laborDispatchUrl: '',
        annualInspectionReportUrl: '',
        otherUrl: '',
        mobile: '',
        userName: '',
      },

      rules: {
        logo:[{ required: true, trigger: 'blur', message: '请上传LOGO' }],
        name:[{ required: true, trigger: 'blur', message: '请填写中介名称' }],
        mobile:[{ required: true, trigger: 'blur', message: '请填写联系电话' }],
        address:[{ required: true, trigger: 'blur', message: '请选择地址' }],
        scale:[{ required: true, trigger: 'blur', message: '请选择规模' }],
        userName:[{ required: true, trigger: 'blur', message: '请输入管理后台账号' }],
        businessLicenseUrl:[{ required: true, trigger: 'blur', message: '请上传营业执照' }],
        permitUrl:[{ required: true, trigger: 'blur', message: '请上传经营许可证' }],
        laborDispatchUrl:[{ required: true, trigger: 'blur', message: '请上传劳务派遣证件' }],
        annualInspectionReportUrl:[{ required: true, trigger: 'blur', message: '请上传年检报告' }],

      },
      formLoading: false,
    }
  },
  props:['id','closeDialog'],
  methods:{
    //上传文件配置
    uploadImageMe(file, insertFn){
      // file 即选中的文件
      // 自己实现上传，并得到图片 url alt href
      let name = file.name;
      let suffix = file.type.split("/")[1];
      name = name + '.' + suffix;
      let formdata = new FormData()
      formdata.append("file", file)
      //上传方法
      uploadApi(formdata).then(res => {
        console.log(res)
        // 最后插入图片
        insertFn(res , res, res )
      })

    },
    handleAvatarSuccess(res, file) {
      this.form.logo = res.data;
    },
    handleAvatarSuccess2(res, file) {
      this.form.businessLicenseUrl = res.data;
    },
    handleAvatarSuccess3(res, file) {
      this.form.permitUrl = res.data;
    },
    handleAvatarSuccess4(res, file) {
      this.form.laborDispatchUrl = res.data;
    },
    handleAvatarSuccess5(res, file) {
      this.form.annualInspectionReportUrl = res.data;
    },
    handleAvatarSuccess6(res, file) {
      this.form.otherUrl = res.data;
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onCreated2(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    submit(){
      this.$refs.placeCodeForm.validate(valid => {
        if (valid) {
          const loading=this.$loading({
            text:'提交中'
          })
          const form=JSON.parse(JSON.stringify(this.form));
          editIntermediaryApi(form).then((res)=>{
            this.$message.success('保存成功');
            this.closeDialog(0);
          }).catch(()=>{
            this.$message.error('保存失败');
          }).finally(()=>{
            loading.close();
          })
        } else {
          return false
        }
      })
    },
    getScaleType() {
      getScaleApi().then((res) => {
        this.scaleTypeOption = res
      }).catch((err) => {
        this.$message.error('规模分类加载失败')
      }).finally(() => {
        this.placeTypeLoading = false
      })
    },
    getDetail(){
      getIntermediaryByIdApi({id:this.id}).then((res)=>{
        this.form=res;
        if(res.userName)
        {
          this.isEdit = true
        }
      }).finally(()=>{
        this.formLoading=false;
      })
    },
  },
  watch: {

  },
  mounted() {
    window.addEventListener('message', (event) =>{
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        this.form.latitude=loc.latlng.lat;
        this.form.longitude=loc.latlng.lng;
        this.form.address=loc.poiname
        axios.get(`https://apis.map.qq.com/ws/geocoder/v1/?location=${loc.latlng.lat},${loc.latlng.lng}&key=RSQBZ-R2NER-KFMWS-W6OZN-UXMTE-H4BIF`).then((res)=>{
          console.log(res);
        })
      }
    }, false);
    this.getScaleType();
    if(this.id){
      this.getDetail();
    }

  },

}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
.w-e-bar.w-e-bar-show.w-e-toolbar{
  border: 1px solid;
}
.w-e-scroll{
  border: 1px solid;
}
</style>
<style scoped>
/*
*让select撑开
*/
.el-select,.el-cascader{
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
